package com.xiaoai.juc;

import java.util.concurrent.CountDownLatch;

public class Tbf_CountDownLatch {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(2);
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("子线程1开始执行....");
                //模拟子线程执行任务
                try {
                    Thread.sleep(30);
                }catch (Exception e){
                    e.printStackTrace();
                }
                System.out.println("子线程1执行完任务....");
                countDownLatch.countDown();//每次减一
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("子线程2开始执行....");
                //模拟子线程执行任务
                try {
                    Thread.sleep(30);
                }catch (Exception e){
                    e.printStackTrace();
                }
                System.out.println("子线程2执行完任务....");
                countDownLatch.countDown();//每次减一
            }
        }).start();
        countDownLatch.await(); //计数不为0，以下代码一直等待
        System.out.println("主线程开始执行任务....");
        for (int i=0;i<5;i++){
            System.out.println("main:"+i);
        }
    }
}